package com.jinqing.wuchuang.service.impl;

import com.jinqing.wuchuang.config.JwtFilter;
import com.jinqing.wuchuang.entity.AuthUser;
import com.jinqing.wuchuang.mapper.AuthUserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

@Service
public class UserDetailServiceImpl implements UserDetailsService {

    private final static Logger logger = LoggerFactory.getLogger(UserDetailServiceImpl.class);
    @Autowired
    private AuthUserMapper authUserMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        /**
         * 这个类的功能是通过名字返回一个userdetail对象,这个对象用于验证
         * 调用多个dao装配user
         * 把user的用户名 密码 和权限都装配进去
         */

        if(username == null  || "".equals(username)){
            throw new RuntimeException("用户不能为空");
        }
        AuthUser user =  authUserMapper.getAuthUserByUsername(username);
        ArrayList<String> authorities = (ArrayList<String>) authUserMapper.getAuthorityByRole(user.getRoles().get(0));
        logger.info("用管理员登录所有的权限有"+user.getRoles());

        for(String s:authorities){
            user.getRoles().add(s);
        }
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在!");
        }
        return user;
    }
    }

